/**
 * @fileoverview User Authentication API Service
 * 
 * This module handles all user authentication and profile-related API calls.
 * It provides a clean interface for authentication operations such as login,
 * logout, registration, and profile management.
 * 
 * @module api/userApi
 * @author Your Organization
 * @license MIT
 */

import service from './axiosApiInstance';

/**
 * Authentication token storage key
 * @constant {string}
 * @private
 */
const TOKEN_STORAGE_KEY = 'token';

/**
 * User Authentication and Profile API Service
 */
const userApi = {
  /**
   * Authenticate user with username and password
   * 
   * @async
   * @param {Object} credentials - User login credentials
   * @param {string} credentials.username - Username
   * @param {string} credentials.password - Password
   * @returns {Promise<Object>} Authentication result with token
   * @throws {Error} If authentication fails or network error occurs
   * 
   * @example
   * try {
   *   const result = await userApi.authenticate({
   *     username: 'testuser',
   *     password: 'testpassword'
   *   });
   *   
   *   if (result.success) {
   *     // User is now logged in
   *     console.log('Token:', result.data.token);
   *   }
   * } catch (error) {
   *   console.error('Authentication failed:', error.message);
   * }
   */
  authenticate: async (credentials) => {
    try {
      const { username, password } = credentials;
      
      // Input validation
      if (!username || !password) {
        throw new Error('Both username and password are required');
      }
      
      const response = await service.post('/login', { username, password });
      
      // Save authentication token if login was successful
      if (response.success && response.data?.token) {
        localStorage.setItem(TOKEN_STORAGE_KEY, response.data.token);
      }
      
      return response;
    } catch (error) {
      console.error('Authentication failed:', error);
      throw error;
    }
  },
  
  /**
   * End user session and clear authentication data
   * 
   * @async
   * @returns {Promise<void>}
   * @throws {Error} If logout operation fails
   * 
   * @example
   * try {
   *   await userApi.endSession();
   *   // User is now logged out
   * } catch (error) {
   *   console.error('Logout failed:', error.message);
   * }
   */
  endSession: async () => {
    try {
      // Optional: Call server-side logout endpoint if needed
      // await service.post('/logout');
      
      // Clear authentication data
      localStorage.removeItem(TOKEN_STORAGE_KEY);
    } catch (error) {
      console.error('Logout operation failed:', error);
      throw error;
    }
  },
  
  /**
   * Create a new user account
   * 
   * @async
   * @param {Object} userInfo - New user information
   * @param {string} userInfo.username - Desired username
   * @param {string} userInfo.password - Account password
   * @param {string} [userInfo.email] - Email address
   * @param {Object} [userInfo.profile] - Additional profile information
   * @returns {Promise<Object>} Registration result
   * @throws {Error} If registration fails
   * 
   * @example
   * try {
   *   const result = await userApi.createAccount({
   *     username: 'newuser',
   *     password: 'securepassword',
   *     email: 'user@example.com'
   *   });
   *   
   *   if (result.success) {
   *     // Account created successfully
   *   }
   * } catch (error) {
   *   console.error('Account creation failed:', error.message);
   * }
   */
  createAccount: async (userInfo) => {
    try {
      const { username, password, email, ...profileData } = userInfo;
      
      // Input validation
      if (!username || !password) {
        throw new Error('Username and password are required');
      }
      
      return await service.post('/register', { 
        username, 
        password, 
        email, 
        ...profileData 
      });
    } catch (error) {
      console.error('Account creation failed:', error);
      throw error;
    }
  },
  
  /**
   * Fetch current user profile information
   * 
   * @async
   * @returns {Promise<Object>} User profile data
   * @throws {Error} If profile retrieval fails or user is not authenticated
   * 
   * @example
   * try {
   *   const profile = await userApi.fetchUserProfile();
   *   console.log('User profile:', profile);
   * } catch (error) {
   *   console.error('Could not retrieve profile:', error.message);
   * }
   */
  fetchUserProfile: async () => {
    try {
      if (!userApi.isAuthenticated()) {
        throw new Error('User is not authenticated');
      }
      
      return await service.get('/user/info');
    } catch (error) {
      console.error('Profile retrieval failed:', error);
      throw error;
    }
  },
  
  /**
   * Check if user has an authentication token
   * 
   * @returns {boolean} True if user has a valid token stored
   * 
   * @example
   * if (userApi.isAuthenticated()) {
   *   // Show user dashboard
   * } else {
   *   // Show login screen
   * }
   */
  isAuthenticated: () => {
    return Boolean(localStorage.getItem(TOKEN_STORAGE_KEY));
  },
  
  /**
   * Get the current authentication token
   * 
   * @returns {string|null} The authentication token or null if not authenticated
   */
  getToken: () => {
    return localStorage.getItem(TOKEN_STORAGE_KEY);
  }
};

export default userApi; 